﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Deeper.Common.Web
{
    public static class CookiesHelper
    {
        private static HttpCookie getCookies(HttpContext ctx, string strName)
        {
            HttpCookie cookie = ctx.Request.Cookies[strName];
            if (cookie == null) cookie = new HttpCookie(strName);
            return cookie;
        }
        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(this HttpContext ctx, string strName)
        {
            HttpCookie cookie = getCookies(ctx, strName);
            return cookie.Value;
        }


        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="strValue">过期时间(天)</param>
        public static void WriteCookie(this HttpContext ctx, string strName, string strValue, int expires = 0)
        {
            HttpCookie cookie = getCookies(ctx, strName);
            cookie.Value = strValue;
            if (expires > 0) cookie.Expires = DateTime.Now.AddDays(expires);
            ctx.Response.AppendCookie(cookie);
        }


        /// <summary>
        /// 删除Cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        public static void RemoveCookies(this HttpContext ctx, string strName)
        {

            if (null != ctx.Request.Cookies && null != ctx.Request.Cookies[strName])
                ctx.Request.Cookies[strName].Expires = DateTime.Now.AddDays(-10);
        }
    }
}
